package com.thread.threadfirst.encrypt;

import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 */
public class MD5Operator {

    public static MessageDigest messageDigest;

    static {
        try {
            messageDigest = MessageDigest.getInstance("md5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    //转字符串
    public static String getStr(byte[] bytes){
        String temp="";
        for (int i=0;i<bytes.length;i++) {
            String hexString = Integer.toHexString(bytes[i] & 0xff);//将二进制转成16进制的字符串。
            if (hexString.length()==1)
                temp = temp + "0" + hexString;
            else temp = temp + hexString;
        }
        return temp.toUpperCase();
    }

    public static String getMD5(String str){
        if (StringUtils.isNotBlank(str)) {
            byte[] bytes = messageDigest.digest(str.getBytes());
            return getStr(bytes);
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(MD5Operator.getMD5("hello"));
        System.out.println(getMD5("hejuan"));
    }
}
